package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.entity.OrderBaseEntity;
import com.yuanfeng.order.entity.OrderInvoiceAddressEntity;
import com.yuanfeng.order.entity.OrderInvoiceInfoEntity;
import com.yuanfeng.order.feign.BaseServiceClient;
import com.yuanfeng.order.mapper.OrderInvoiceInfoMapper;
import com.yuanfeng.order.service.OrderBaseService;
import com.yuanfeng.order.service.OrderInvoiceInfoService;
import com.yuanfeng.order.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.yuanfeng.commoms.util.TokenUtils.checkToken;

/**
 * @ClassName OrderInvoiceInfoServiceImpl
 * @Description  订单发票表
 * @Author cyp
 * @Date 2023-06-25 10:33:24
 * @Version 1.0
 **/
@Service
public class OrderInvoiceInfoServiceImpl extends ServiceImpl<OrderInvoiceInfoMapper, OrderInvoiceInfoEntity>
        implements OrderInvoiceInfoService {
    @Autowired
    private OrderBaseService orderBaseService;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Override
    public ResponseResult applyInvoice(Map<Object, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            if (!param.containsKey("invoiceHead")) {
                return ResponseResult.success(BizCodeEnume.INVOICE_ADDRESS_TITLE_IS_NULL.getMsg());
            }
            //申请开票将发票状态置为审核中
            param.put("invoiceStatus", 1);
            if (!param.containsKey("invoiceType")) {
                param.put("invoiceType", 0);
            }
            if (!param.containsKey("invoiceHeadType")) {
                param.put("invoiceHeadType", 1);
            }
            BigDecimal orderAmount = orderBaseService.getById(param.get("orderId").toString()).getOrderPaymentAmount();
            param.put("invoiceAmount", orderAmount);
            //重新申请发票
            if (null != param.get("invoiceId")) {
                this.baseMapper.updateInvoiceInfo(param);
            } else {
                //第一次申请发票
                this.baseMapper.insertInvoiceInfo(param);
            }
            OrderInvoiceInfoEntity entity = this.baseMapper.selectOne(new LambdaQueryWrapper<OrderInvoiceInfoEntity>()
                    .eq(OrderInvoiceInfoEntity::getOrderId, param.get("orderId").toString()));
            orderBaseService.update(null, new LambdaUpdateWrapper<OrderBaseEntity>()
                    .eq(OrderBaseEntity::getOrderId, param.get("orderId").toString())
                    .set(OrderBaseEntity::getInvoiceId, param.get("invoiceId") == null ? entity.getInvoiceId() : param.get("invoiceId").toString())
                    .set(OrderBaseEntity::getInvoiceStatus, param.get("invoiceStatus").toString()));
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult applyInvoiceBatch(Map<Object, Object> param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.get("token").toString());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        } else {
            param.put("userId",userInfo.getUserId());
        }
        try {
            List<String> orderIds = (ArrayList<String>) param.get("orderIds");
            for(String orderId:orderIds) {
                param.put("orderId",orderId);
                //申请开票将发票状态置为审核中
                Integer invoiceStatus = this.baseMapper.getInvoiceStatus(orderId);
                if(null == invoiceStatus){
                    invoiceStatus = 0;
                }
                param.put("invoiceStatus", invoiceStatus);
                BigDecimal orderAmount = this.baseMapper.getInvoiceAmount(param);
                Integer invoiceId = this.baseMapper.getInvoiceId(param);
                param.put("invoiceAmount",orderAmount);
                param.put("invoiceId",invoiceId);
                this.baseMapper.updateInvoiceInfo(param);
                this.baseMapper.updateInvoiceStatus(param);
            }
          return ResponseResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult queryInvoiceDetail(Map<Object, Object> param) {
        String token = (String) param.get("token");
        ResponseResult tokenResult = checkToken(token);
        if (tokenResult.getCode() == CommonStatusEnum.FAIL.getCode()) {
            return tokenResult;
        } else {
            param.put("userId", tokenResult.getData().toString());
        }
        try {
            OrderInvoiceDetailVO orderInvoiceDetailEntity = this.baseMapper.queryInvoiceDetail(param);

            Integer provinceId = orderInvoiceDetailEntity.getAddressProvince();
            Integer cityId = orderInvoiceDetailEntity.getAddressCity();
            Integer areaId = orderInvoiceDetailEntity.getAddressArea();
            if (provinceId != null && cityId != null && areaId != null) {
                String preCompleteAddress = baseServiceClient.getAddressString(provinceId, cityId, areaId).getData().toString();
                String completeAddress = preCompleteAddress + orderInvoiceDetailEntity.getAddressDetail();
                orderInvoiceDetailEntity.setPreCompleteAddress(preCompleteAddress);
                orderInvoiceDetailEntity.setCompleteAddress(completeAddress);
            }
            return ResponseResult.success(orderInvoiceDetailEntity);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryPlatformOrderInvoiceList(Map<String, Object> param) {
        if(null != param.get("invoiceType") && 100 == (Integer)param.get("invoiceType")){
            param.put("invoiceType",null);
        }
        if(null != param.get("invoiceStatus") && 100 == (Integer)param.get("invoiceStatus")){
            param.put("invoiceStatus",null);
        }
        //分页查询数据
        IPage<PlatformOrderInvoiceVO> page = this.baseMapper.queryPlatformOrderInvoiceInfo(new Query<PlatformOrderInvoiceVO>().getPage(param),param);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryPlatformInvoiceDetail(Map<Object, Object> param) {
        PlatformOrderInvoiceDetailVO platformOrderInvoiceDetailEntity = this.baseMapper.queryPlatformInvoiceDetail(param);
        OrderInvoiceAddressVO address = new OrderInvoiceAddressVO();
        address.setAddressProvince(platformOrderInvoiceDetailEntity.getAddressProvince());
        address.setAddressCity(platformOrderInvoiceDetailEntity.getAddressCity());
        address.setAddressArea(platformOrderInvoiceDetailEntity.getAddressArea());
        address.setAddressDetail(platformOrderInvoiceDetailEntity.getAddressDetail());
        if(null != address) {
            String completeAddress = baseServiceClient.getAddressString(address.getAddressProvince(), address.getAddressCity(), address.getAddressArea()).getData().toString();
            address.setPreCompleteAddress(completeAddress);
            completeAddress = completeAddress + address.getAddressDetail();
            address.setCompleteAddress(completeAddress);
        }
        platformOrderInvoiceDetailEntity.setAddress(address);
        return ResponseResult.success(platformOrderInvoiceDetailEntity);
    }

    @Override
    @Transactional
    public ResponseResult auditInvoiceForSeller(Map<Object, Object> param) {
        ResponseResult rr = new ResponseResult();
        String token = (String) param.get("token");
        UserInfoVO ui=ParseTokenUtils.getUserInfoByToken(token);
        Integer shopId = Integer.valueOf(ui.getShopId());
        if(null == shopId){
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
            return rr;
        }
        rr = checkToken(token);
        if (rr.getCode() == 2) {
            return rr;
        } else {
            param.put("userId", rr.getData().toString());
        }
        try {
            this.baseMapper.auditInvoiceForSeller(param);
            this.baseMapper.updateOrderInvoiceStatus(param);
            rr.setCode(CommonStatusEnum.SUCCESS.getCode());
            rr.setMessage(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg());
        } catch (Exception e) {
            rr.setCode(CommonStatusEnum.FAIL.getCode());
            rr.setMessage(BizCodeEnume.OPERATION_FAILED.getMsg());
            log.error(e.getMessage());
        }
        return rr;
    }

    @Override
    public ResponseResult querySellerInvoiceDetail(Map<Object, Object> param) {
        String token = (String) param.get("token");
        // 根据code存储用户信息
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
        UserInfoVO userInfo = dto.getUser();
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        param.put("userId", userInfo.getUserId());
        try {
            SellerOrderInvoiceDetailVO sellerOrderInvoiceDetailEntity = this.baseMapper.querySellerInvoiceDetail(param);

            OrderInvoiceAddressEntity address = new OrderInvoiceAddressEntity();
            address.setAddressProvince(sellerOrderInvoiceDetailEntity.getAddressProvince());
            address.setAddressCity(sellerOrderInvoiceDetailEntity.getAddressCity());
            address.setAddressArea(sellerOrderInvoiceDetailEntity.getAddressArea());
            address.setAddressDetail(sellerOrderInvoiceDetailEntity.getAddressDetail());
            if(null != address) {
                String completeAddress = getAddress(address.getAddressProvince() + "", address.getAddressCity() + "", address.getAddressArea() + "");
                address.setPreCompleteAddress(completeAddress);
                completeAddress = completeAddress + address.getAddressDetail();
                address.setCompleteAddress(completeAddress);
            }
            sellerOrderInvoiceDetailEntity.setAddress(address);
            return ResponseResult.success(sellerOrderInvoiceDetailEntity);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(2,"操作异常"+e.getMessage());
        }
    }

    private String getAddress(String provinceId, String cityId, String districtId) {
        if ((provinceId == null || provinceId.equals(""))
                && (cityId == null || cityId.equals(""))
                && (districtId == null || districtId.equals(""))) {
            return "";
        }
        String provinceName = baseServiceClient.queryProvinceport(provinceId);
        String cityName = baseServiceClient.queryProvinceport(cityId);
        String districtName = baseServiceClient.queryProvinceport(districtId);
        return provinceName + cityName + districtName;
    }

}
